import 'dart:async';

import 'package:flutter/material.dart';

import '../../../Utils/ColorUtil.dart';

class Marquee extends StatefulWidget {
  final String text;
  final TextStyle? textStyle;
  final Duration scrollDuration;
  final Duration startScrollDuration;
  final double scrollSpeed;

  const Marquee(
      this.text,
      {super.key,
        this.textStyle = const TextStyle(
          fontSize: 16,
          color: ColorUtil.colorWhite,
        ),
        this.scrollDuration = const Duration(milliseconds: 50),
        this.startScrollDuration = const Duration(milliseconds: 3000),
        this.scrollSpeed = 1.0,
      });

  @override
  State<Marquee> createState() => _MarqueeState();
}

class _MarqueeState extends State<Marquee> {
  late ScrollController _controller;
  late bool _forward;
  late double _scrollPosition;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _forward = true;
    _scrollPosition = 0.0;
    _startScrollAnimation();
  }

  Timer? _timer;
  void _startScrollAnimation() {
    _timer = Timer.periodic(widget.scrollDuration, (timer) async {
      if (_forward) {
        _scrollPosition += widget.scrollSpeed;
        if (_scrollPosition > _controller.position.maxScrollExtent) {
          _scrollPosition = _controller.position.maxScrollExtent;
        }
        if (_scrollPosition == _controller.position.maxScrollExtent) {
          await Future.delayed(widget.startScrollDuration);
          _forward = false;
        }
      } else {
        _scrollPosition -= widget.scrollSpeed;
        if (_scrollPosition < 0) {
          _scrollPosition = 0;
        }
        if (_scrollPosition == 0) {
          await Future.delayed(widget.startScrollDuration);
          _forward = true;
        }
      }

      if (mounted) {
        _controller.animateTo(
          _scrollPosition,
          duration: widget.scrollDuration,
          curve: Curves.linear,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return IgnorePointer(
      child: SingleChildScrollView(
        physics: const BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        controller: _controller,
        child: Row(
          children: [
            Text(
              widget.text,
              style: widget.textStyle,
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    if (_timer != null) _timer!.cancel();
    super.dispose();
  }
}
